<template>
	<view style="width: 100vw;height: 100vh;background-color: #e2e2e2;">
		<scroll-view scroll-y="true" style="width: 100%;height: 100%;">
			<!-- 顶部按钮 -->
			<view class="cu-custom" :style="[{height:CustomBar + 'px'}]">
				<view class="cu-bar fixed flex justify-between align-center bg-white" :style="{height:CustomBar+'px',paddingTop:StatusBar+'px'}" style="font-size: 32rpx;" >
					<text class=" cuIcon-back margin-left" @click="back" style="font-size: 40rpx;"></text>
					<text class=" text-blue margin-right" @click="send()">发布</text>
				</view>
			</view>
			<!-- 课程信息 -->
			<view>
				<!-- 课程标题 -->
				<view style=" padding: 20rpx 32rpx; line-height: 64rpx;" class="bg-white">
					<textarea v-model="course.title" style="color: #131415;font-size: 40rpx;font-weight: bold;"
						auto-height placeholder="请输入课程标题（5-30个字）*" maxlength="30"
						placeholder-style="font-size: 40rpx;color: #aa5500;" />
				</view>
				<!-- 封面 -->
				<view style="padding: 24rpx 32rpx;" >
					<uni-file-picker fileMediatype="image" mode="grid" limit="1" :auto-upload="false" :value="course.cover?[{url:course.cover}]:[]"
						@select="selectImg" @delete="deleteCover" title="最多选择1张封面图 *"
						:image-styles="{height:'200rpx', width: '200rpx'}">
					</uni-file-picker>
				</view>
				<!-- 课程描述 -->
				<jinEdit class="bg-white" placeholder="请输入课程描述(富文本编辑) *"  @editOk="editOk" :uploadFileUrl="uploadUrl" :html="course.description" ref="jinEdit">
				</jinEdit>
				<!-- 好物链接 -->
				<view @click="addGoodsLink" style="margin-top: 24rpx; margin-bottom: 24rpx; padding: 30rpx 32rpx;" class="flex align-center justify-between bg-white">
					<view class="flex align-center">
					   <text class="cuIcon-goods text-blue" style="font-size: 40rpx;"></text>
					   <text style="font-size: 32rpx; margin-left: 20rpx;">添加好物链接（可选）</text>
					</view>
	                <view class="cuIcon-right text-blue" style="font-size: 38rpx;"></view>
				</view>
			</view>
			<!-- 标签选择 -->
			<view class="cu-form-group" style="font-size: 32rpx;" >
				<view class="title" style="font-size: 32rpx;">标签选择</view>
				<view class="picker" @click="openSelect">
					请选择<text class="cuIcon-right"></text>
				</view>
			</view>
			<tki-tree ref="tree" :range="range" rangeKey="title" :multiple="true" @confirm="confirm"
				confirmColor="#4e8af7" />
			<!-- 添加章节 -->
			<view style="margin-top:24rpx;padding: 30rpx 32rpx;" class="bg-white">
				<text style="font-size: 34rpx; line-height: 40rpx;color:#aa5500;">添加课程视频*</text>
				<view v-for="(item,index) in course.courseChapterVos" :key="index" class="margin-top" style="border-top: 4rpx solid #aaaaaa;">
					<view class="flex justify-between align-center">
						<input v-model="item.title" placeholder="请输入章节标题(5-30个字) *"  maxlength="30" class="margin-top-sm flex-sub"></input>
						<button class="cu-btn block bg-gradual-green margin-top-sm margin-left-sm" @click="deleteChapter(index)">
							<text class="cuIcon-delete text-white"></text>
						</button>
					</view>	

					<!-- 视频上传 -->
					<view style="margin-top: 15rpx " >
						<uni-file-picker fileMediatype="video" mode="list" limit="1" :auto-upload="false" :value="item.videoUrl?[{name:item.name,
					url:item.videoUrl}]:[]"
							@select="selectVideo($event,index)" @delete="deleteVideo(item)" title="请选择本节视频" :list-styles="listStyles">
						</uni-file-picker>
					</view>
				</view>
				<view class="margin-top margin-bottom" >
				   <button class="cu-btn block bg-gradual-green " @click="addChapter">添加章节</button>
				</view>
			</view>
			<!-- 占位区 -->
			<view style="width: 100%;height: 100rpx;"></view>
		</scroll-view>
	</view>
</template>

<script>
	import jinEdit from '../../components/jin-edit/jin-edit.vue'
	export default {
		components: {
			jinEdit
		},
		data() {
			return {
			    range: [], //多选
				listStyles: {
					// 是否显示边框
					border: true,
					// 是否显示分隔线
					dividline: true,
					// 线条样式
					borderStyle: {
						width: 1,
						color: 'blue',
						radius: 2
					}
				},
				uploadUrl: "http://xuewenbao.cn:38880/xwb/edu/file/uploadOSS",
				course: {
					classArray:[],//标签数组，数据回显
					title: "",
					teacherId: this.$store.getters.userid,
					cover: "",
					price:0,
					description: "",
					goodVo:null,
					courseChapterVos: [],
					subjectList:[]
				},
			}
		},
		onLoad() {
			// 获取本地存储
			if(uni.getStorageSync('course')){
				this.course=uni.getStorageSync('course')
			}
		    //获取分类 
			this.getSubject().then(res => {
				Promise.all(this.getChildSubject(res)).then(res2 => {
					this.range = res2
					if (this.range && this.course.classArray) {
						//寻找已被选中的标签,并进行数据回显
						this.course.classArray.forEach(item => {
							if (item.parents.length == 0) {
								// 寻找一级分类
								let first = this.range.find(el => {
									return el.id == item.id
								})
								first.checked = true
							} else if (item.parents.length == 1) {
								// 寻找二级分类
								let first = this.range.find(el => {
									return el.id == item.parents[0].id
								})
								let second = first.children.find(el => {
									return el.id == item.id
								})
								second.checked = true
							} else {
								// 寻找三级分类
								let first = this.range.find(el => {
									return el.id == item.parents[0].id
								})
								let second = first.children.find(el => {
									return el.id == item.parents[1].id
								})
								let third = second.children.find(el => {
									return el.id == item.id
								})
								third.checked = true
							}
						})
						// console.log(this.range)
					}
				})
			})	
		},
		onShow() {
			//获取好物链接
			if (uni.getStorageSync('goods')) {
				this.course.goodVo = uni.getStorageSync('goods')
				this.$tip.success('链接添加成功')
			}
			else{
			  this.course.goodVo=null	
			}
		},
		methods: {
			confirm(e) {
				this.course.classArray = e
				e.forEach(item => {
					this.course.subjectList.push(item.id)
				})
			},
			openSelect() {
				this.$refs.tree._show()
			},
			//获取一级分类
			getSubject() {
				return new Promise((resolve, reject) => {
					this.$http.get('/edu/onesubject/getAllOneSubject').then(res => {
						resolve(res.data.result)
					})
				})
			},
			// 获取子分类
			getChildSubject(array) {
				let proArray = [];
				for (let i = 0; i < array.length; i++) {
					proArray.push(new Promise((resolve, reject) => {
						this.$http.get('/edu/child-subject/getAllChildSubject/' + array[i].id).then(res => {
							let {
								result
							} = res.data
							result.forEach(val => {
								val.children = val.subjectVoList
								delete val.subjectVoList
							})
							array[i].children = result
							resolve(array[i])
						})
					}))
				}
				return proArray;
			},
			addGoodsLink(){
				//保存本地存储用来数据回显
				this.$refs.jinEdit.release()
				uni.setStorageSync('course',this.course)
				this.$Router.push({name:'addGoodsLink'})
			},
			send(){
				this.$refs.jinEdit.release()
				console.log(this.course)
				this.$http.post('/edu/course/addCourse',this.course).then((res)=>{
					console.log(res)
					if(res.statusCode === 200) {
						uni.removeStorageSync('course')
						uni.removeStorageSync('goods')
						this.$tip.success('课程创作成功!');
						this.$Router.push({name:'createCenter'})
					}else {
						this.$tip.error('课程创作失败!');
					}
				})
			},
			editOk(e){
				// console.log(e)
				this.course.description=e.html
			},
			//上传封面
			async selectImg(e) {
				console.log(e)
				uni.showLoading({
					title: '正在上传中...'
				})
				for (let temp of e.tempFiles) {
					// 图片上传服务器
					await uni.uploadFile({
						url: this.uploadUrl,
						filePath: temp.path,
						name: "file",
						formData: {
							'biz': 'cover'
						},
						success: res => {
							//上传完成后处理
							let data = JSON.parse(res.data)
							if (data.success) {
								// console.log("cover上传成功", data.message)
								this.course.cover = data.message
								console.log(this.course.cover)
							} else {
								console.log("cover上传失败", data.message)
							}
							uni.hideLoading()
						},

					});
				}
			},
			//上传视频
			async selectVideo(e,index) {
				console.log(e)
				console.log(index)
				uni.showLoading({
					title: '正在上传中...'
				})
				for (let temp of e.tempFiles) {
					// 图片上传服务器
					await uni.uploadFile({
						url: this.uploadUrl,
						filePath: temp.path,
						name: "file",
						formData: {
							'biz': 'video'
						},
						success: res => {
							//上传完成后处理
							let data = JSON.parse(res.data)
							if (data.success) {
								console.log("video上传成功", data.message)
								this.course.courseChapterVos[index].name=temp.name
								this.course.courseChapterVos[index].videoUrl = data.message
							} else {
								console.log("video上传失败", data.message)
							}
							uni.hideLoading()
						},

					});
				}
			},
			deleteVideo(item) {
				// todo
				console.log("删除video", item);
				item.videoUrl=""
			},
			deleteCover(e) {
				// todo
				// console.log("删除cover图片", e);
				this.$http.post('/edu/file/deleteOss',this.course.cover).then(res =>{
					if(res.data.success){
						this.$tip.success('删除成功')
						this.course.cover=""
					}
				})
				
			},
			deleteChapter(index){
				this.course.courseChapterVos.splice(index,1)
			},
			addChapter(e){
				// console.log(e)
				let chapter={
					title:"",
					videoUrl:"",
					name:""
				}
				this.course.courseChapterVos.push(chapter)
			},
			back(){
				uni.removeStorageSync('course')
				uni.removeStorageSync('goods')
				this.$Router.push({name:'createCenter'})
			}
		}
	}
</script>

<style>
</style>
